var express = require('express');
var router = express.Router();
var bcrypt = require('bcryptjs');
var UUID = require('uuid');

var redis = require('../db/redis.js');

/* GET home page. */
router.get('/', function(req, res, next) {
	res.render('index', {
		title: 'Express'
	});
});

router.post('/login', function(req, res, next) {
	redis.getUser(req.body.username, (err, data) => {
		if(data && bcrypt.compareSync(req.body.password, data.password)) {
			delete data.password;
			var time = new Date().getTime();
			var at = JSON.parse(JSON.stringify(data));
			at.exp = 3 * 60 * 1000 + time;
			at.token = UUID.v1();
			at.username = data.username
			redis.islinkExisted(at.username, function(err, reply) {
				console.log(reply)
				if(reply){
					redis.delAt(reply);
					redis.delLink(at.username);
				}
				redis.linkUserToAt(at.username, at.token);
				redis.putAt(at, () => {
					res.header('Authorization', at.token);
					res.send({
						'msg': 'success',
						'user': data
					})
				});
			})
		} else {
			res.json({
				'err': 'username or password was incorrect.'
			})
		}
	})

});

router.post('/logout', function(req, res, next) {
	redis.delAt(res.locals._at, () => {
		res.send({
			'msg': 'success'
		})
	});
});

module.exports = router;